package com.yyfax.ph.personal.bindapply;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import butterknife.BindView;
import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;
import com.yyfax.common.CLog;
import com.yyfax.common.recycler.StatesAdapter;
import com.yyfax.common.recyclerview.Divider;
import com.yyfax.common.recyclerview.FooterLoadMoreView;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.adapter.BaseRetryRecyclerAdapter;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.personal.authority.jpush.PushInfoReceiver;

import java.util.List;

/**
 * 绑定申请页面
 * Created by ZhangXian on 2017/11/8.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */

public class BindApplyActivity extends BaseYYFaxActivity implements BindApplyPresenter.View,
		BaseRetryRecyclerAdapter.RetryClickListener, OnRefreshListener, OnLoadMoreListener, BindApplyAdapter.BindApplyItemClickListener {
	private static final String TAG = "BindApplyActivity";
	private static final int LOADER_ID_BIND = 108;
	@BindView(R.id.bind_apply_lv)
	IRecyclerView mBindApplyLv;

	private FooterLoadMoreView mLoadMoreView;

	private BindApplyPresenter mPresenter;
	private BindApplyAdapter mAdapter;

	private BaseRetryRecyclerAdapter statesAdapter;

	private int mPageNum = 1;
	private int mPageSize = 20;

	private DialogBase dialog;
	private boolean mNeedRefresh = false;


	public static void start(Activity aty) {
		Intent intent = new Intent(aty, BindApplyActivity.class);
		aty.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportLoaderManager().initLoader(LOADER_ID_BIND, null, this);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.bind_apply_activity;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (null != intent && intent.hasExtra(PushInfoReceiver.FROM_PUSH_FLAG))
			mNeedRefresh = intent.getBooleanExtra(PushInfoReceiver.FROM_PUSH_FLAG, false);
		CLog.i(TAG, "onCreate mNeedRefresh = " + mNeedRefresh);
	}

	@Override
	public void initContentView() {
		setBtnRightVisible(false);
		setTitle(R.string.bind_apply);
		mBindApplyLv.setLayoutManager(new GridLayoutManager(this, 1));
		mBindApplyLv.addItemDecoration(new Divider(DensityUtil.dip2px(this, 10), YJPH.getInstance().color(R.color.color_efefef), false, 0, 0, 0, 0, 0));

		mLoadMoreView = (FooterLoadMoreView) mBindApplyLv.getLoadMoreFooterView();
		View noNetworkLayout = getLayoutInflater().inflate(R.layout.state_view_no_network, mBindApplyLv, false);
		View emptyLayout = getLayoutInflater().inflate(R.layout.bind_apply_state_view_no_data, mBindApplyLv, false);
		mAdapter = new BindApplyAdapter();
		mAdapter.setBindApplyItemClickListener(this);
		mBindApplyLv.setAdapter(mAdapter);
		statesAdapter = new BaseRetryRecyclerAdapter(mAdapter, null, emptyLayout, noNetworkLayout);
		statesAdapter.setRetryClickListener(this);
		mBindApplyLv.setIAdapter(statesAdapter);
		mBindApplyLv.setOnRefreshListener(this);
		mBindApplyLv.setOnLoadMoreListener(this);
		mBindApplyLv.post(new Runnable() {
			@Override
			public void run() {
				mBindApplyLv.setRefreshing(true);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		CLog.i(TAG, "onResume mNeedRefresh = " + mNeedRefresh);
		if (mNeedRefresh) {
			mNeedRefresh = false;
			mBindApplyLv.post(new Runnable() {
				@Override
				public void run() {
					mBindApplyLv.setRefreshing(true);
				}
			});
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		onRefresh();
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		nm.cancelAll();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if ((null != dialog && dialog.isShowing())) {
			dialog.dismiss();
		}
		dialog = null;
		getSupportLoaderManager().destroyLoader(LOADER_ID_BIND);
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new BindApplyPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (BindApplyPresenter) data;
		mPresenter.attach(this);
	}

	@Override
	public void onRefresh() {
		mBindApplyLv.setRefreshing(true);
		loadPage(true);
	}

	@Override
	public void onLoadMore() {
		if ((mAdapter.getCount() % mPageSize) == 0) {
			mLoadMoreView.setStatus(FooterLoadMoreView.Status.LOADING);
			loadPage(false);
		} else {
			mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
			showToast(R.string.has_no_more);
		}
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		refreshFinish();
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				statesAdapter.setState(StatesAdapter.STATE_ERROR);
			}
		});
	}

	@Override
	public void onRetry() {
		onRefresh();
	}

	private void loadPage(boolean isRefresh) {
		mPageNum = isRefresh ? 1 : ++mPageNum;
		mPresenter.getApplyAccounts(mPageNum, mPageSize, isRefresh);
	}

	private void refreshFinish() {
		mBindApplyLv.post(new Runnable() {
			@Override
			public void run() {
				mBindApplyLv.setRefreshing(false);
			}
		});
	}

	//下拉刷新
	@Override
	public void refreshSuccess(List<BindApplyModel.ApplyListBean> list) {
		refreshFinish();
		if (null != list && list.size() > 0) {
			statesAdapter.setState(StatesAdapter.STATE_NORMAL);
			mAdapter.removeAll();
			mAdapter.addData(list);
			mAdapter.notifyDataSetChanged();
			mBindApplyLv.scrollToPosition(0);
			if ((list.size() % mPageSize) > 0 && mPageNum != 1) {//如果第一页不满20条
				showToast(R.string.has_no_more);
			}
		} else {
			statesAdapter.setState(StatesAdapter.STATE_EMPTY);
		}
	}

	//上拉加载
	@Override
	public void loadmoreSuccess(List<BindApplyModel.ApplyListBean> list) {
		if (null == list || list.size() == 0) {
			mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
			showToast(R.string.has_no_more);
		} else {
			statesAdapter.setState(StatesAdapter.STATE_NORMAL);
			mAdapter.addData(list);
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void getSubAccountFailure(String tips) {
		mPageNum--;
		refreshFinish();
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		if (mPageNum == 1) {
			statesAdapter.setState(StatesAdapter.STATE_ERROR);
			showToast(R.string.load_failed);
		}
	}

	//处理子账号申请成功
	@Override
	public void handleBindSuccess(String type) {
		if (!TextUtils.isEmpty(type) && "0".equals(type)) {
			showToast("绑定子账户成功");
		}
		onRefresh();
	}

	//处理子账号申请失败
	@Override
	public void handleBindFailure(String tips) {
		showToast(tips);
		onRefresh();
	}

	@Override
	public void handleBindWarning(String tips) {//页面过期，弹出toast提示并刷新
		showToast(tips);
		onRefresh();
	}

	//点击"接受"或者"拒绝"子账户的绑定申请
	@Override
	public void onDetailItemClick(final String id, String phone, final int type) {
		switch (type) {
			case 0://接受
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E003);
				mPresenter.handleBind(id, String.valueOf(type));
				break;
			case 1://拒绝
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E004);
				if ((null != dialog && dialog.isShowing())) {
					return;
				}
				dialog = new DialogBase(this, "拒绝" + phone + "的绑定申请？", null, "取消", "拒绝",
						new DialogBase.BottomTwoClickListener() {
							@Override
							public void onCancelClick(DialogBase dialog) {
								dialog.dismiss();//取消
							}

							@Override
							public void onConfirmClick(DialogBase dialog) {
								dialog.dismiss();
								mPresenter.handleBind(id, String.valueOf(type));
							}
						}
				);
				dialog.show();
				break;
			default:
				break;
		}
	}
}
